import React, { useState, useEffect } from 'react';
import { Card, Form, Button, Input, Space, Select, Radio, Col, message } from 'antd';
import { QuillEditor, MarkDownEditor } from 'components';
import { connect } from 'dva';
import { Prompt } from 'react-router-dom';
import { getFilePrefix } from 'config';
import { history } from 'umi';

const Article = ({ dispatch, tagList, userInfo, article }) => {
    const [form] = Form.useForm();
    const [isDirty, setDirty] = useState(false);
    const [type, setType] = useState('md');

    // 处理编辑器类型切换
    const handleModeChange = (e) => {
        setType(e.target.value);
    };

    useEffect(() => {
        if (article) {
            setType(article.markdownContent || !article.content ? 'md' : 'quill');
            form.setFieldsValue(article);
            if (article.markdownContent) form.setFieldsValue({ connect: '' });
            if (article.status === 3) form.setFieldsValue({ status: 1 });
        }
    }, [form, article]);

    // 监听页面离开提示
    useEffect(() => {
        const handleBeforeUnload = event => {
            if (isDirty) {
                const message = "您有未保存的更改，确定要离开吗？";
                event.returnValue = message;
                return message;
            }
        };
        setDirty(false);
        window.addEventListener('beforeunload', handleBeforeUnload);
        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, [location.pathname]);

    // 表单内容变更时设置为“true”
    const onValuesChange = changedValues => {
        setDirty(true);
    };

    // 提交表单
    const addArticle = (values) => {
        if (!values.markdownContent && !values.content) {
            message.error('请填写内容')
            return;
        }
        setDirty(false);
        const payload = {
            ...values,
            authorId: userInfo.userId,
            type: type,
            articleId: article?.articleId,
        };
        const actionType = article?.articleId ? "article/updateArticle" : "article/addArticle";
        dispatch({ type: actionType, payload });
        history.push('/manageCenter/articleManage');
        form.resetFields();
    };

    // 文件上传逻辑处理
    const onFileUpload = (fileList) => {
        return new Promise((resolve, reject) => {
            dispatch({
                type: "article/updateUploadFile",
                payload: { fileData: fileList },
                callback: result => {
                    if (result.code === 0) {
                        resolve(getFilePrefix() + result.data);
                    } else {
                        reject(result.msg);
                    }
                }
            });
        });
    };

    return (
        <>
            <Prompt when={isDirty} message="当前页面有未保存的更改，确定要离开吗？" />
            <Card>
                <Col span={6} offset={18}>
                    <Radio.Group onChange={handleModeChange} value={type} style={{ borderRadius: '10px' }}>
                        <Radio.Button value="md">MarkDown编辑器</Radio.Button>
                        <Radio.Button value="quill">富文本编辑器</Radio.Button>
                    </Radio.Group>
                </Col>
                <Form
                    form={form}
                    onValuesChange={onValuesChange}
                    onFinish={addArticle}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                >
                    <Form.Item label="文章标题" name="title" rules={[{ required: true, message: '请输入文章标题' }]}>
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item label="文章标签" name="tagIds" rules={[{ required: true, message: '请选择至少一个文章标签' }]}>
                        <Select mode="multiple" placeholder="请选择文章标签(可搜索)" style={{ width: 400 }}
                            options={tagList.map(option => ({ value: option.tagId, label: option.tagName }))} />
                    </Form.Item>
                    {type === 'md' ? (
                        <Form.Item name="markdownContent" label="文章内容">
                            <MarkDownEditor
                                onFileUpload={onFileUpload}
                                value={form.getFieldValue('markdownContent')}
                                onChange={(newText) => form.setFieldsValue({ markdownContent: newText })}
                            />
                        </Form.Item>
                    ) : (
                        <Form.Item label="文章内容" name="content">
                            <QuillEditor onFileUpload={onFileUpload} videoLabel={true} />
                        </Form.Item>
                    )}
                    <Form.Item name="status" label="文章状态" rules={[{ required: true }]}>
                        <Radio.Group options={[{ label: "发布", value: 1 }, { label: "保存为草稿", value: 0 }]} />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size="large" type="primary" htmlType="submit">提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </>
    );
};

export default connect(({ article, user }) => ({
    article: article.article,
    tagList: article.tagList,
    userInfo: user.userInfo,
}))(Article);